package com.yun.algorithm.dynamicprogramming.leetcode;

import java.util.ArrayList;
import java.util.List;

public class E05Leetcode22 {

    public List<String> generateParenthesis1(int n) {
        ArrayList<String>[] dp = new ArrayList[n + 1];
        dp[0] = new ArrayList<>(List.of(""));
        dp[1] = new ArrayList<>(List.of("()"));
        for (int j = 2; j < n + 1; j++) {
            for (int i = 0; i < j; i++) {
                System.out.printf("(%d,%d)\t", i, j - 1 - i);
                for (String k1 : dp[i]) {
                    for (String k2 : dp[j - 1 - i]) {
                        dp[j].add("(" + k1 + ")" + k2);
                    }
                }
            }
            System.out.println();
        }
        System.out.println(dp[n]);
        return null;
    }

    public List<String> generateParenthesis(int n) {
        ArrayList<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        dfs("", n, n, res);
        return res;
    }

    private void dfs(String curStr, int left, int right, ArrayList<String> res) {
        if (left == 0 && right == 0) {
            res.add(curStr);
            return;
        }
        if (left > right) {
            return;
        }
        if (left > 0) {
            dfs(curStr + "(", left - 1, right, res);
        }
        if (right > 0) {
            dfs(curStr + ")", left, right - 1, res);
        }
    }

    public static void main(String[] args) {
        E05Leetcode22 code = new E05Leetcode22();
        System.out.println(code.generateParenthesis(3));
    }
}
